package com.wzc.order.service.impl;

import com.wzc.basic.service.impl.BaseServiceImpl;
import com.wzc.basic.util.AjaxResult;
import com.wzc.basic.util.PageList;
import com.wzc.order.domain.OrderPetAcquisition;
import com.wzc.order.dto.OrderDto;
import com.wzc.order.mapper.OrderPetAcquisitionMapper;
import com.wzc.order.query.OrderPetAcquisitionQuery;
import com.wzc.order.service.IOrderPetAcquisitionService;
import com.wzc.org.domain.Employee;
import com.wzc.org.domain.Shop;
import com.wzc.org.mapper.EmployeeMapper;
import com.wzc.org.mapper.ShopMapper;
import com.wzc.pet.domain.Pet;
import com.wzc.pet.mapper.PetMapper;
import com.wzc.pet.mapper.SearchMasterMsgMapper;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Service
public class OrderPetAcquisitionServiceImpl extends BaseServiceImpl<OrderPetAcquisition> implements IOrderPetAcquisitionService {

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private PetMapper petMapper;
    /**
     * 订单 分页 查询
     * @param query
     * @param id
     * @return
     */
    @Override
    public PageList<OrderPetAcquisition> queryQuery(OrderPetAcquisitionQuery query, Long id) {
        // 根据当前登录人的 id 查询 employee（查询登录人信息）
        Employee employee = employeeMapper.loadByLogininfoId(id);
        if(employee.getShop_id() != null){ // 当前登录人没有 shop_id 则为店铺店员
            // 当前登录人是店员是，查询他所在的店铺
            Shop shop = shopMapper.loadById(employee.getShop_id());
            if(shop.getAdmin_id() != employee.getShop_id()){ // 当前登录人既不是店长也不是店员（平台管理员）
                query.setEmpId(employee.getId()); // 将平台管理员 id 存到query
            }
            // 不管是店长还是店员都要将其对应店铺 id 存到 query
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }


    /**
     * 订单确认
     * @param dto
     */
    @Override
    public void confirm(OrderDto dto) throws Exception {
        // 获取订单中的信息
        Long id = dto.getId();
        BigDecimal money = dto.getMoney();
        Integer payType = dto.getPayType();
        /**
         * 订单确认后：
         * 1. 修改订单状态，金额, 支付方式
         * 2. 修改寻主消息状态
         * 3. 修改 pet 金额
         */
        // 查询当前订单信息
        OrderPetAcquisition orderPetAcquisition = orderPetAcquisitionMapper.loadById(id);
        if (orderPetAcquisition != null){ // 订单不为空进行消费
            // 获取consumer对象
            DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("order_consumer_group");
            // 设置地址nameseriveraddress
            consumer.setNamesrvAddr("localhost:9876");
            // 订阅信息
            consumer.subscribe("order","*");
            // 回调实现类来处理从broker拉取回来的消息
            consumer.registerMessageListener(new MessageListenerConcurrently() {
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                    for (MessageExt messageExt : list) {
                        System.out.println(new String(messageExt.getBody(), StandardCharsets.UTF_8));
                    }
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
            });
            // 启动
            consumer.start();
        }
        // 修改信息
        orderPetAcquisition.setState(2);
        orderPetAcquisition.setPrice(money);
        orderPetAcquisition.setPaytype(payType);
        // 保存修改后的信息
        orderPetAcquisitionMapper.update(orderPetAcquisition);

        // 修改寻主消息状态(将订单中的状态赋值到寻主信息)
        searchMasterMsgMapper.updateState(orderPetAcquisition.getSearch_master_msg_id());

        // 修改pet金额
        Pet pet = petMapper.loadById(orderPetAcquisition.getPet_id()); // 根据订单信息中 pet_id 查询 pet
        pet.setCostprice(money);
        petMapper.update(pet); // 保存修改的pet
    }

    /**
     * 写一个方法，发送一条包含订单号的消息
     * @param topic
     * @throws Exception
     */
    private AjaxResult sendDelayMsg(String topic) throws Exception {
        // 获取生产者对象
        DefaultMQProducer producer = new DefaultMQProducer("delay_producer_group");
        // 设置nameserver地址
        producer.setNamesrvAddr("localhost:9876");
        // 启动producer
        producer.start();

        Message message = new Message("delay", "hello", "在这编写信息！".getBytes(StandardCharsets.UTF_8));
        message.setDelayTimeLevel(3); // 设置延时级别  10S
        SendResult send = producer.send(message);
        System.out.println(send);
        producer.shutdown();
        return AjaxResult.me();
    }

        /**
         * 取消订单
         * @param id
         */
    @Override
    public void cancel(Long id) {
        /**
         * 1.修改订单状态
         * 2.将寻主信息 shop_id 赋值为 null
         * 3.删除订单生成的 pet 信息
         */
        // 1.修改订单状态
        OrderPetAcquisition orderPetAcquisition = orderPetAcquisitionMapper.loadById(id);
        orderPetAcquisition.setState(-1);
        orderPetAcquisitionMapper.update(orderPetAcquisition);

        // 2.将寻主信息 shop_id 赋值为 null
        // 直接调用拒单操作
        searchMasterMsgMapper.reject(orderPetAcquisition.getSearch_master_msg_id());

        // 3.删除订单生成的 pet 信息
        petMapper.remove(orderPetAcquisition.getPet_id());

    }


}
